package jp.eisbahn.eclipse.plugins.twitterclipse.view;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.ListenerList;

import jp.eisbahn.eclipse.plugins.twitterclipse.TwitterStatus;

public class TwitterStatusList {
	
	private Map<String, TwitterStatus> statusMap;
	
	private Collection<TwitterStatus> previousStatusList;
	
	private Collection<TwitterStatus> currentStatusList;
	
	private ListenerList listenerList;
	
	public TwitterStatusList() {
		super();
		statusMap = new HashMap<String, TwitterStatus>();
		listenerList = new ListenerList();
		previousStatusList = new ArrayList<TwitterStatus>();
		currentStatusList = new ArrayList<TwitterStatus>();
	}
	
	public void addTwitterStatusListListener(TwitterStatusListListener listener) {
		listenerList.add(listener);
	}
	
	public void removeTwitterStatusListListener(TwitterStatusListListener listener) {
		listenerList.remove(listener);
	}
	
	public void statusChanged(List<TwitterStatus> statusList) {
		Collection<TwitterStatus> previousList = statusMap.values();
		boolean changed = false;
		for (TwitterStatus status : statusList) {
			if (statusMap.containsValue(status)) {
				String userId = status.getTwitterUser().getId();
				TwitterStatus existsStatus = statusMap.get(userId);
				if (existsStatus.compareTo(status) <= 0) {
					statusMap.put(userId, status);
					changed = true;
				}
			} else {
				statusMap.put(status.getTwitterUser().getId(), status);
				changed = true;
			}
		}
		if (changed) {
			previousStatusList = previousList;
			currentStatusList = new ArrayList<TwitterStatus>();
			currentStatusList.addAll(statusMap.values());
			Collections.sort((List<TwitterStatus>)currentStatusList);
			Collections.reverse((List<TwitterStatus>)currentStatusList);
			notifyStatusListChanged();
		}
	}

	private void notifyStatusListChanged() {
		Object[] listeners = listenerList.getListeners();
		for (int i = 0; i < listeners.length; i++) {
			((TwitterStatusListListener)listeners[i]).statusListChanged(previousStatusList, currentStatusList);
		}
	}

	public Collection<TwitterStatus> getCurrentStatusList() {
		return currentStatusList;
	}

	public Collection<TwitterStatus> getPreviousStatusList() {
		return previousStatusList;
	}

}
